import { marked } from "marked";
import hljs from 'highlight.js';
import DOMPurify from "dompurify";

// 定义消息类型
export interface ChatMessage {
  sessionId: string;
  role: string;
  part: string;
  isThinking?: boolean;
}

// 定义对话类型
export interface Conversation {
  sessionId: string;
  title: string;
  messages: ChatMessage[];
  lastActive: number;
}

// 配置marked以支持代码高亮
marked.setOptions({
  breaks: true,
  gfm: true,
  highlight: function(code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      return hljs.highlight(lang, code).value;
    }
    return hljs.highlightAuto(code).value;
  },
});

// 渲染 AI 消息（允许代码高亮，但净化 HTML）
export const renderMarkdown = (text: string) => {
  const rawHtml = marked(text);
  return DOMPurify.sanitize(rawHtml);
};

// 渲染用户消息（禁用代码高亮，并转义 HTML）
export const renderUserMarkdown = (text: string) => {
  const escapedText = text
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;");
  return marked(escapedText, {
    breaks: true,
    gfm: true,
    highlight: null, // 禁用代码高亮
  });
};
